#include "unify_core.h"
#include "user_core.h"
#include <sys/stat.h>   
#include <unistd.h>

#define CHECK_INTERVAL		5

extern AIR_APP_INFO_T stMqttMsgInfo;

INT32 dir_link(const INT8* sDir,const INT8* dDir)
{
    DIR *sdir = NULL;    
    struct dirent *ent;
    CHAR sPath[512] = {0}; 
    CHAR dPath[512] = {0};  

    if(access(dDir,F_OK) != 0){
        htkj_system("mkdir -p %s" , dDir);
    }
    sdir = opendir(sDir);
    if (sdir == NULL) {  
        Error("open src DIR %s error",sDir);
        return ERROR;
    }   
    while (1){
        INT32 size = 0;
        pthread_rwlock_rdlock(&stMqttMsgInfo.rwlock);//加读锁
        size = stMqttMsgInfo.videoSize;
        pthread_rwlock_unlock(&stMqttMsgInfo.rwlock); //解锁  
        if(size >= stMqttMsgInfo.block_max_size*1024*1024)
            break; 
        ent = readdir (sdir);
        if (ent <= 0) {  
            break;
        }  
        if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0)) {  
            continue;
        }  
        if(ent->d_name[0] == '.')
            continue;
        sprintf(sPath ,"%s/%s" , sDir,ent->d_name);
        sprintf(dPath ,"%s/%s" , dDir,ent->d_name);
        if ((ent->d_type == DT_REG) || (ent->d_type == DT_LNK)) { //8 10
            pthread_rwlock_wrlock(&stMqttMsgInfo.rwlock);//请求写锁
            if(0 == link(sPath,dPath)){
                unlink(sPath);
                struct stat statbuf;
                if(stat(dPath,&statbuf)==0)
                    stMqttMsgInfo.videoSize += statbuf.st_size/1024;
                INFO("file:%s size:%lu",dPath,statbuf.st_size); 
            }
            size = stMqttMsgInfo.videoSize;            
            pthread_rwlock_unlock(&stMqttMsgInfo.rwlock); //解锁  
            if(size >= stMqttMsgInfo.block_max_size*1024*1024)
                break;       
        }else if(ent->d_type == DT_DIR){
            dir_link(sPath ,dPath);
        }
    }  
    closedir(sdir);    
    return OK;
}
INT32 unifyDatas_task(void *arg)
{
    UINT32 cTime = 0; 
    UINT32 curTime = 0;
    
    htkj_system("mkdir -p %s",UNIFY_BASE_PATH);
    delEmptyDir(UNIFY_BASE_PATH);
    delEmptyDir(UNIFY_BASE_PATH);
    delEmptyDir(UNIFY_BASE_PATH);
    delEmptyDir(UNIFY_BASE_PATH);
    delEmptyDir(UNIFY_BASE_PATH);
    stMqttMsgInfo.videoSize = getPathData_realSize(UNIFY_BASE_PATH);
    
    while(1){
        usleep(500000);//500ms
        curTime = currentTimeGet_int();
        
        if((curTime - cTime) < CHECK_INTERVAL)
            continue;
        cTime = curTime;
        dir_link(stMqttMsgInfo.uploadLinkPath ,UNIFY_BASE_PATH);
    }
    return 0;    
}


